package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;


public class CreationFilmPage extends AnyPage {

	public CreationFilmPage(PageManager pages) {
		super(pages);
	}

	@FindBy(name = "name")
	private WebElement title;
	
	@FindBy(name = "year")
	private WebElement year;
	
	@FindBy (xpath = "//img[@alt='Save']")
	private WebElement saveButton;
	
	@FindBy (xpath = "//label[@class='error']")
	private List<WebElement> errorElements;
	
	@FindBy (xpath = "//label[@for='name']")
	private WebElement labelName;

	@FindBy (xpath = "//label[@for='year']")
	private WebElement labelYear;
	
	public CreationFilmPage setTitle(String text) {
		title.sendKeys(text);
		return this;
	}

	public CreationFilmPage setYear(String text) {
		year.sendKeys(text);
		return this;
	}
	
	public FilmPage clickSaveButton(){
		saveButton.click();
		return pages.filmPage; 
	}
	
	public CreationFilmPage clickSaveWithError(){
		saveButton.click();
		return pages.creationFilmPage; 
	}
	
	public List<String> getErrorFields(){
		// Находим все сообщения об ошибках, если есть запиcываем в массив в каком поле
		List<String> fieldError = new ArrayList<String>();
		 for (WebElement el : errorElements) {
			if( ! el.getAttribute("style").contains("display: none;")){
				fieldError.add(el.getAttribute("for"));
			}
		}
		return fieldError;
	}
	
	public CreationFilmPage ensurePageLoaded() {
		super.ensurePageLoaded();
		wait.until(presenceOfElementLocated(By.cssSelector("form#updateform")));
		return this;
	}
}
